package com.edu.hre.struts.action.pim;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.util.LabelValueBean;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmpReportto;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmpSupervisorUpdateForm;

public class EmpSupervisorUpdateAction extends DispatchAction{
	
	private static final Logger logger = Logger.getLogger(EmpSupervisorUpdateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "empSupervisorUpdate";
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());

		EmpSupervisorUpdateForm beanForm = (EmpSupervisorUpdateForm) form;
		beanForm.setIsAddNew(true);

		if(request.getParameter(StringConstants.BTN_ADD) == null){
			
			int empNum = CommonUtils.getIntParameter("emp_num", request);
			beanForm.setEmpNumber(empNum);

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}  

		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);
		Integer supNumber = CommonUtils.getEmpNumber(beanForm.getSupNumber());
		
		if (supNumber == null || supNumber <= 0) {
			beanForm.setMessage("Supervisor is empty or invalid!");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		if (beanForm.getEmpNumber() == supNumber) {
			beanForm.setMessage("An employee cannot be his/her own subordinate!");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		// Check if the new supervisor already exists on the supervisor list.
		HreEmpReportto tmpReportto = baseService.getFirstPojoAnd(new String[]{"erepSupEmpNumber", "erepSubEmpNumber"},
				new int[]{Compare.EQUAL, Compare.EQUAL},
				new Object[]{supNumber, beanForm.getEmpNumber()}, null, null, 0, HreEmpReportto.class);
		
		if (tmpReportto != null) {
			beanForm.setMessage("The selected employee already exists on the supervisor list.");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		// Check if the new supervisor already exists on the subordinate list.
		tmpReportto = baseService.getFirstPojoAnd(new String[]{"erepSupEmpNumber", "erepSubEmpNumber"},
				new int[]{Compare.EQUAL, Compare.EQUAL},
				new Object[]{beanForm.getEmpNumber(), supNumber}, null, null, 0, HreEmpReportto.class);
		
		if (tmpReportto != null) {
			beanForm.setMessage("The selected employee already exists on the subordinate list. [A supervisor of an employee cannot be his/her subordinate!]");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		HreEmpReportto tmp = new HreEmpReportto();
		tmp.setErepSubEmpNumber(beanForm.getEmpNumber());
		tmp.setErepSupEmpNumber(supNumber);
		tmp.setErepReportingMode(beanForm.getReportingMethod());
		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.INSERT_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		EmpSupervisorUpdateForm beanForm = (EmpSupervisorUpdateForm) form;
		beanForm.setIsAddNew(false);
		
		if(request.getParameter(StringConstants.BTN_EDIT) == null){
			
			int id = CommonUtils.getIntParameter("id", request);
			HreEmpReportto tmp = baseService.getFirstPojo("id", Compare.EQUAL, id, null, null, 0, HreEmpReportto.class);
			
			if (tmp == null) {
				beanForm.setMessage(StringConstants.BLANK);
				initFormBean(beanForm);
				return mapping.findForward(ACTION_NAME);
			}
			
			beanForm.setId(id);
			beanForm.setEmpNumber(tmp.getErepSubEmpNumber());
			beanForm.setSupNumber(CommonUtils.getEmpNameAndUsername(tmp.getErepSupEmpNumber()));
			beanForm.setReportingMethod(tmp.getErepReportingMode());

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);
		Integer supNumber = CommonUtils.getEmpNumber(beanForm.getSupNumber());
		
		if (supNumber == null || supNumber <= 0) {
			beanForm.setMessage("Supervisor is empty or invalid!");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		if (beanForm.getEmpNumber() == supNumber) {
			beanForm.setMessage("An employee cannot be his/her own subordinate!");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		// Check if the new supervisor already exists on the supervisor list.
		HreEmpReportto tmpReportto = baseService.getFirstPojoAnd(new String[]{"erepSupEmpNumber", "erepSubEmpNumber"},
				new int[]{Compare.EQUAL, Compare.EQUAL},
				new Object[]{supNumber, beanForm.getEmpNumber()}, null, null, 0, HreEmpReportto.class);
		
		if (tmpReportto != null && beanForm.getId() != tmpReportto.getId()) {
			beanForm.setMessage("The selected employee already exists on the supervisor list.");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		// Check if the new supervisor already exists on the subordinate list.
		tmpReportto = baseService.getFirstPojoAnd(new String[]{"erepSupEmpNumber", "erepSubEmpNumber"},
				new int[]{Compare.EQUAL, Compare.EQUAL},
				new Object[]{beanForm.getEmpNumber(), supNumber}, null, null, 0, HreEmpReportto.class);
		
		if (tmpReportto != null) {
			beanForm.setMessage("The selected employee already exists on the subordinate list. [A supervisor of an employee cannot be his/her subordinate!]");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		HreEmpReportto tmp = baseService.getFirstPojo("id", Compare.EQUAL, beanForm.getId(), null, null, 0, HreEmpReportto.class);
		if (tmp == null) {
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		tmp.setErepSubEmpNumber(beanForm.getEmpNumber());
		tmp.setErepSupEmpNumber(supNumber);
		tmp.setErepReportingMode(beanForm.getReportingMethod());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		response.getWriter().write(
				 "<script language=\"javascript\">\n" +
						" parent.dw.close();" + 
						 " var param = parent.document.createElement('input'); " +
						 " param.type = 'hidden'; " +
						 " param.name = 'id'; " +
						 " param.value = " + tmp.getErepSubEmpNumber() +  ";" +
						 " parent.document.forms[0].appendChild(param);" +
						" parent.document.forms[0].submit(); \n" +
				 "</script>");
		return null;
	}
	
	private void initFormBean (EmpSupervisorUpdateForm beanForm) {

		int empNumber = beanForm.getEmpNumber();

		List<HreEmployee> listEmployee = baseService.getPojosAnd(new String[]{"empNumber", "isDeleted"}, new int[]{Compare.NOT_EQUAL, Compare.EQUAL}, new Object[]{empNumber, false}, null, null, -1, 0, HreEmployee.class);
		
		List<LabelValueBean> allEmps = new ArrayList<LabelValueBean>();
		for (HreEmployee hreEmp: listEmployee) {
			
			String displayName = hreEmp.getEmpLastname() + StringConstants.SPACE
					+ hreEmp.getEmpMiddleName() + StringConstants.SPACE
					+ hreEmp.getEmpFirstname() + StringConstants.SPACE;

			if (hreEmp.getMainUsername() != null) {
				displayName += "[" + hreEmp.getMainUsername() + "]";
			}

			allEmps.add(new LabelValueBean(displayName, hreEmp.getEmpNumber() + StringConstants.BLANK));
		}
		
		beanForm.setAllMethods(ComboBoxInit.getAllReportingMethods(false));
		beanForm.setAllEmployees(allEmps);
	}
}
